package com.heima.search.service.impl;

import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IApUserSearchService;
import com.heima.search.service.IArticleSearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private IApUserSearchService userSearchService;
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        // 判断输入的关键字是否为空,为空的话返回空的数据列表
        if (dto == null || StringUtils.isEmpty(dto.getSearchWords())) {
            return new PageResponseResult(dto.getPage(), dto.getSize(), 0L, new ArrayList<ApArticleSearch>());
        }
        // 分页查询
        // 传入关键字
        Pageable page = PageRequest.of(dto.getPage().intValue() - 1, dto.getSize(), Sort.Direction.DESC, "publishTime");
        QueryBuilder query = QueryBuilders.matchQuery("title", dto.getSearchWords());
        Page<ApArticleSearch> searchPage = articleRepository.search(query, page);
        // 构建通用的分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                searchPage.getTotalElements(), searchPage.getContent());

        //添加异步操作
        User user = MediaThreadLocalUtil.get();
        Integer userId=null;
        if (user!=null){
            userId=user.getUserId();
        }
        userSearchService.saveSearchRecord(dto.getSearchWords(),userId,dto.getEquipmentId());



        return result;

    }
}
